//
//  InviteShareAlertView.swift
//  MT
//
//  Created by 陈悦 on 2020/5/15.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import YHPhotoKit
import RxSwift
import RxCocoa
import Kingfisher

extension UIView {
    func asImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)
        return renderer.image { rendererContext in
            layer.render(in: rendererContext.cgContext)
        }
    }
}

class InviteShareAlertView: UIView {
    
//    var model: MineInfoModel? {
//        didSet {
//            if model != nil {
//                var coverImg: String = ""
//                if let img = model?.imgList?.first?.coverImg {
//                    coverImg = img
//                } else if let img = model?.headerUrl {
//                    coverImg = img
//                }
//
//                coverImage.mtSetImage(coverImg, defaultPlaceholderIcon60x60)
//                nameLab.text = model?.nickname
//                levelLab.text = "M\(model?.levelId ?? 0)"
//                qrcodeImage.image = generateQRCode(str: "\(shareUrl)\(model?.id ?? -1)")
//            }
//        }
//    }
    
    @IBOutlet weak var qrcodeImage: UIImageView!
    @IBOutlet weak var toFriendBtn: UIButton!
    @IBOutlet weak var levelLab: UILabel!
    @IBOutlet weak var nameLab: UILabel!
    @IBOutlet weak var coverImage: UIImageView!
    @IBOutlet weak var toMomentBtn: UIButton!
    @IBOutlet weak var saveBtn: UIButton!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var closeBtn: UIButton!
    @IBOutlet var contentView: UIView!
    @IBAction func closeView(_ sender: Any) {
        UIView.animate(withDuration: 0.3, animations: {
            self.alpha = 0
        }) { (flag) in
            self.removeFromSuperview()
        }
    }
    
    private func downLoadShareImage(platformtype: PlatformType, shareType: ShareType ) {
        var coverImg: String = ""
            
        if let img = UserDefaults.MTUserCenter.headerUrl.storedString {
            coverImg = img
        }
        
        if coverImg != "" {
            let observer: Observable<UIImage> = rx_downloadImage(u: coverImg)
            observer.subscribe { [weak self] (element) in
                guard let weakSelf = self else { return }
                if let s = element.element {
                    DispatchQueue.main.async {
                        weakSelf.coverImage.image = s
                        //if let shareImage = weakSelf.bgView.asImage() {
                            if WXApi.isWXAppInstalled() {
                                let shareModle: ShareModel = ShareModel()
                                shareModle.shareImageObj = weakSelf.bgView.asImage()
                                MTShareManager.share(platformtype: platformtype, sharemodel: shareModle, shareType: shareType)
                            } else {
                                AlertManager.presentAlertView(message: "分享需要安装微信")
                            }
    //                    }
                    }
                }
            }.disposed(by: globalDisposedBag)
        } else {
            self.coverImage.image = UIImage(named: defaultPlaceholderIcon1024)
            if WXApi.isWXAppInstalled() {
                let shareModle: ShareModel = ShareModel()
                shareModle.shareImageObj = self.bgView.asImage()
                MTShareManager.share(platformtype: platformtype, sharemodel: shareModle, shareType: shareType)
            } else {
                AlertManager.presentAlertView(message: "分享需要安装微信")
            }
        }
    }
    
    func rx_downloadImage(u: String) -> Observable<UIImage> {
        return Observable.create({ observer -> Disposable in
            if let url = URL(string: u) {
                MBProgressHUD_JChat.showLoading(self)
                KingfisherManager.shared.cache.retrieveImageInDiskCache(forKey: u, options: [.onlyFromCache]) { (result) in
                    MBProgressHUD_JChat.dismiss(self)
                    switch result {
                    case .success(let image):
                        if image == nil {
                            ImageDownloader.default.downloadImage(with: url, options: KingfisherParsedOptionsInfo(.none)) { (result) in
                                switch result {
                                case .success(let imageLoading):
                                    /// cache Image 下载都下载了, 顺便缓存一下吧
                                    KingfisherManager.shared.cache.store(imageLoading.image, forKey: u)
                                    observer.onNext(imageLoading.image)
                                    observer.onCompleted()
                                case .failure(let error):
                                    observer.onError(error)
                                }
                            }
                        } else {
                            observer.onNext(image!)
                            observer.onCompleted()
                        }
                    case .failure(_):
                        ImageDownloader.default.downloadImage(with: url, options: KingfisherParsedOptionsInfo(.none)) { (result) in
                            MBProgressHUD_JChat.dismiss(self)
                            switch result {
                            case .success(let imageLoading):
                                /// cache Image 下载都下载了, 顺便缓存一下吧
                                KingfisherManager.shared.cache.store(imageLoading.image, forKey: u)
                                observer.onNext(imageLoading.image)
                                observer.onCompleted()
                            case .failure(let error):
                                observer.onError(error)
                            }
                        }
                    }
                }
            } else {
                let image = UIImage(named: defaultPlaceholderIcon60x60)!
                observer.onNext(image)
                observer.onCompleted()
            }
            return Disposables.create()
        })
    }

    @IBAction func toFriendClick(_ sender: Any) {
        downLoadShareImage(platformtype: .wechatType, shareType: .shareImage)
    }
    @IBAction func toSessionClick(_ sender: Any) {
        downLoadShareImage(platformtype: .WechatTimeLine, shareType: .shareImage)
    }
    @IBAction func saveClick(_ sender: Any) {
        if let img = self.bgView.asImage().imageCornerRadius(8) {
            saveImageToPhotoLibrary(image: img)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        // 加载xib
        contentView = (Bundle.main.loadNibNamed("InviteShareAlertView", owner: self, options: nil)?.last as! UIView)
        // 设置frame
        contentView.frame = frame
        contentView.backgroundColor = UIColor.black.withAlphaComponent(0.5)
//        NSToolObjectClass.animationWithAlertViewWithView(allView: tipView)
        
        //bgView.layer.cornerRadius = 8
        
        coverImage.contentMode = .scaleAspectFill
        bgView.layer.cornerRadius = 8
        bgView.clipsToBounds = true
        coverImage.clipsToBounds = true
        
        levelLab.layer.cornerRadius = 6
        levelLab.clipsToBounds = true
        // 添加上去
        addSubview(contentView)
        setData()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setData() {
        var coverImg: String = ""
        let imglist = UserDefaults.MTUserCenter.imgList.storedValue as? [UserMediaListModel]
        if let img = imglist?.first?.coverImg {
            coverImg = img
        } else if let img = UserDefaults.MTUserCenter.headerUrl.storedString {
            coverImg = img
        }
        
        coverImage.mtSetImage(coverImg, defaultPlaceholderIcon60x60)
        nameLab.text = UserDefaults.MTUserCenter.nickname.storedString
        levelLab.text = "M\(UserDefaults.MTUserCenter.levelId.storedInt )"
        qrcodeImage.image = generateQRCode(str: "\(shareUrl)\(UserDefaults.MTUserCenter.id.storedInt)")
    }
    
    private func saveImageToPhotoLibrary(image: UIImage?) {
        
        guard let img = image else {
            return
        }
        // 判断权限
        switch PHPhotoLibrary.authorizationStatus() {
        case .authorized:
            saveImage(image: img)
        case .notDetermined:
            PHPhotoLibrary.requestAuthorization { [weak self](status) in
                if status == .authorized {
                
                    self?.saveImage(image: img)
                } else {
                    debugPrint("User denied")
                }
            }
            
        case .restricted, .denied:
            if let url = URL.init(string: UIApplication.openSettingsURLString) {
            
            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url, options: [:], completionHandler: nil)
            }
        }
            
        default:
            break
        }
    }
    
    private func saveImage(image: UIImage) {
        
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: image)
        }, completionHandler: {(isSuccess, error) in
            
            DispatchQueue.main.async {
                
                if isSuccess {// 成功
                    //AlertManager.presentAlertView(message:"保存成功")
                    MBProgressHUD_JChat.show(text: "保存成功", view: self, 1)
                    DispatchQueue.main.after(1.1) {
                        UIView.animate(withDuration: 0.25, animations: {
                            self.alpha = 0
                        }) { (flag) in
                            self.removeFromSuperview()
                        }
                    }
                }
            }
        })
    }
}

extension InviteShareAlertView {
    ///生成二维码
    func generateQRCode(str: String) -> UIImage? {
        
        let data = str.data(using: String.Encoding.utf8)
        
        guard let filter = CIFilter(name: "CIQRCodeGenerator") else { return nil }
        
        filter.setValue(data, forKey: "inputMessage")
        
        let transform = CGAffineTransform(scaleX: 9, y: 9)
        
        guard let output = filter.outputImage?.transformed(by: transform) else { return nil }
        
        return UIImage(ciImage: output)
    }
}

extension UIView {
   /**
    * @method 截取View一部分,产生新的图片
    *
    * @param  shotSize(要截取的区域)
    *
    * @return image(截取后的图片)
    */
   func screenShot(shotSize: CGSize) -> UIImage? {
       //1.开启上下文
       
       UIGraphicsBeginImageContextWithOptions(shotSize, true, 0)
       
       //2.绘制图形,把layer上的内容绘制到上下文当中
       
       self.layer.render(in: UIGraphicsGetCurrentContext()!)
       
       let newImage = UIGraphicsGetImageFromCurrentImageContext()
       
       //3.关闭上下文
       
       UIGraphicsEndImageContext()
       
       return newImage
   }
}
